package rpc.core;

import java.util.Map;
import java.util.Objects;


/*********
 *
 *
 *@author 197
 *@date 2020/8/3 10:36
 *
 **/


public class FlowRes {

  private final FlowMap data = new FlowMap();

  public FlowRes() {
  }

  public FlowRes(Map<String, Object> data) {
    this.data.toMap().putAll(data);
  }

  public FlowRes ok() {
    this.append("retCode", 0);
    return this;
  }

  public FlowRes append(String key, Object value) {
    data.append(key, value);
    return this;
  }

  public FlowRes fail(int retCode) {
    this.append("retCode", retCode);
    return this;
  }

  public boolean isFail() {
    return !isSucc();
  }

  public boolean isSucc() {
    return this.data.l("retCode") == 0;
  }

  public FlowRes msg(String value) {
    data.append("retMsg", value);
    return this;
  }

  public FlowRes msg(Exception e) {
    data.append("retMsg", e.getMessage());
    return this;
  }

  public FlowRes append(Object... kv) {
    if (Objects.nonNull(kv)) {
      for (int i = 0; i < kv.length; i += 2) {
        if (!(kv[i] instanceof String)) {
          throw new RuntimeException("append key must String");
        }
      }
      for (int i = 0; i < kv.length - 1; i += 2) {
        data.append(kv[i].toString(), kv[i + 1]);
      }
    }
    return this;
  }

  public Map<String, Object> toMap() {
    return this.data.toMap();
  }

  public String retMsg() {
    return this.ns("retMsg");
  }

  private String ns(String key) {
    return this.data.ns(key);
  }

  public long retCode() {
    return this.data.l("retCode");
  }
}
